package com.myrpc.consumer.discovery.zk;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import javax.annotation.PostConstruct;

import org.I0Itec.zkclient.ZkClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.myrpc.common.Contants;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class ServiceDiscovery {

	@Value("${registry.address}")
	private String registryAddress;
	
	@Autowired
	ChannelSessionManager channelSessionManager;
	

	private ZkClient client;
	

	@PostConstruct
	public void init() {
		client = connectServer();
		if (client != null) {
			watchNode(client);
		}
	}

	private  ConcurrentHashMap<String, String>  nodesDatas= new ConcurrentHashMap<String, String>();
	

	private ZkClient connectServer() {
		ZkClient client = new ZkClient(registryAddress, 10000, 10000);
		return client;
	}
	
	  private void watchNode(final ZkClient client) {
	        List<String> nodeList = client.subscribeChildChanges(Contants.ZK_REGISTRY_PATH, (s, nodes) -> {
	            log.info("监听到子节点数据变化{}",JSONObject.toJSONString(nodes));
	            nodesDatas.clear();
	            getNodeData(nodes);
	            log.info("已发现子节点和服务列表...{}", JSONObject.toJSONString(nodesDatas));
	            channelSessionManager.watchNodeChannels(nodesDatas);
	            
	        });
	        
	        //下面的代码第一次才会执行
	        log.info("nodeList:{}",nodeList);
	        getNodeData(nodeList);
	        
	        log.info("已发现子节点和服务列表...{}", JSONObject.toJSONString(nodesDatas));
	        channelSessionManager.watchNodeChannels(nodesDatas);
	    }
	  
	  private  ConcurrentHashMap<String, String>  getNodeData(List<String> nodes){
	       // log.info("/myrpc子节点数据为:{}", JSONObject.toJSONString(nodes));///myrpc子节点数据为:["provider0000000000"]
	        for(String node:nodes){
	            String address = client.readData(Contants.ZK_REGISTRY_PATH+"/"+node);
	            //addressList.add(address);//127.0.0.1:10000
	            nodesDatas.put(node, address);
	        }
	        return nodesDatas;
	    }

}
